package com.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.time.LocalDateTime;

/**
 * @Author Cc
 * @Date 2024-03-11
 */
public class GsonUtil {
    /**
     * 序列化对象
     *
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        if (object == null) {
            return "";
        }
        Gson gson = new GsonBuilder()
                // 注册类型适配器
//                .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter())
                // 忽略空字段
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .serializeNulls()
                .create();
        return gson.toJson(object);
    }

    /**
     * 反序列化
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T fromJson(String json, Class<T> clazz) {
        if (json == null || "".equals(json.trim())) {
            return null;
        }
        Gson gson = new GsonBuilder()
//                .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter())
                // 忽略空字段
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .serializeNulls()
                .create();
        return gson.fromJson(json, clazz);
    }
}
